<template>
  <div style="background-color: #f5f5f5; padding: 20px; min-height: 100vh;">
    <!-- 页面标题 -->
    <div style="text-align: left; margin-bottom: 20px;">
      <i class="el-icon-picture-outline" style="color: #409EFF; font-size: 36px; margin-right: 10px;"></i>
      <span style="font-size: 24px; color: #333; font-weight: bold;">{{this.title}}</span>
    </div>

    <!-- 图片列表 -->
    <el-row :gutter="20">
      <!-- 显示图片列表 -->
      <el-col
          v-for="(item, index) in menuItems"
          :key="index"
          :span="4"
          style="margin-bottom: 20px;"
      >
        <div class="photo-item">
          <img
              :src="item.url"
              alt="图片"
              class="photo-img"
              @click="viewPhoto(item.url)"
          />
          <div class="photo-actions">
            <i class="el-icon-download photo-icon" @click.stop="downloadPhoto(item.url)"></i>
            <i class="el-icon-delete photo-icon" @click.stop="deletePhoto(item.id)"></i>
          </div>
        </div>
      </el-col>

      <!-- 上传图片入口 -->
      <el-col :span="4" style="margin-bottom: 20px;">
        <el-upload
            class="upload-item"
            :action="$baseUrl + '/file/upload'"
            :headers="{ 'x-token': user?.token || '' }"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
        >
          <i class="el-icon-plus upload-icon"></i>
          <p>点击上传图片</p>
        </el-upload>
      </el-col>
    </el-row>

    <!-- 查看图片大图 -->
    <el-dialog
        :visible.sync="viewPhotoDialog"
        width="40%"
        :close-on-click-modal="true"
    >
      <img :src="currentPhoto" alt="预览图片" style="width: 100%; border-radius: 8px;" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Photo",
  data() {
    return {
      user: JSON.parse(localStorage.getItem("honey-user") || "{}"), // 获取用户信息
      menuItems: [], // 图片数据列表
      viewPhotoDialog: false, // 控制预览大图弹框
      currentPhoto: "", // 当前预览的大图
      title:this.$route.query.name
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    loadData() {
      this.$request
          .post("/photos/list", { albumId: this.$route.query.id })
          .then((res) => {
            if (res.code === "200") {
              this.menuItems = res.data;
            } else {
              this.$message.error("图片加载失败");
            }
          })
          .catch(() => {
            this.$message.error("请求失败，请检查网络连接！");
          });
    },
    viewPhoto(url) {
      this.currentPhoto = url;
      this.viewPhotoDialog = true;
    },
    downloadPhoto(url) {
      const link = document.createElement("a");
      link.href = url;
      link.download = "下载图片";
      link.click();
    },
    deletePhoto(photoId) {
      this.$confirm("此操作将永久删除该图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.$request
                .post("/photos/delete", { photoId })
                .then((res) => {
                  if (res.code === "200") {
                    this.$message.success("图片删除成功");
                    this.menuItems = this.menuItems.filter((item) => item.id !== photoId);
                  } else {
                    this.$message.error(res.message || "删除失败");
                  }
                })
                .catch(() => {
                  this.$message.error("删除请求失败，请重试");
                });
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
    },
    handleUploadSuccess(response) {
      if (response.code === "200" && response.data && response.data.length > 0) {
        const newPhoto = { id: response.data[0]?.id, url: response.data[0]?.url };
        if (newPhoto.url) {
          this.menuItems.push(newPhoto);
          this.$request
              .post("/photos/add", {
                url: newPhoto.url,
                albumId: this.$route.query.id,
                userId: this.user.userId,
              })
              .then((res) => {
                if (res.code === "200") {
                  this.$message.success("图片上传成功");
                } else {
                  this.$message.error(res.message || "图片上传失败");
                }
              })
              .catch(() => {
               this.$message.error("上传请求失败，请重试");
              })
        } else {
          this.$message.error("上传响应数据格式不正确！");
        }
      } else {
        this.$message.error(response.message || "图片上传失败");
      }
    },
    beforeUpload(file) {
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isImage) {
        this.$message.error("上传图片格式必须是 JPG 或 PNG!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("上传图片大小不能超过 20MB!");
        return false;
      }

      return true;
    },
  },
};
</script>

<style scoped>
.photo-item {
  background: #fff;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: relative;
  cursor: pointer;
}

.photo-img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.photo-actions {
  display: flex;
  justify-content: space-around;
  margin-top: 5px;
}

.photo-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.photo-icon:hover {
  color: #409eff;
}

.upload-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: #f5f5f5;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-item:hover {
  background: #e6f7ff;
  border-color: #409eff;
}

.upload-icon {
  font-size: 36px;
  color: #8c939d;
}
</style>
